<?php

require_once 'Add/Setup/Password/Save/Interface.php';

class Add_Setup_Password_Save_Adapter_Db extends Add_Setup_Password_Save_Abstract
{
    const IDENTITY_NOT_FOUND = 'identityNotFound';
    const CREDENTIAL_INVALID = 'credentialInvalid';
    protected $_messageTemplates = array(
        self::IDENTITY_NOT_FOUND => "A record with the supplied identity could not be found.",
        self::CREDENTIAL_INVALID => "Supplied credential is invalid.",
    );
    
    public function save()
    {
        $result = array(
            'code'        => Add_Setup_Password_Save_Result::FAILURE,
            'messages'    => array(),
        );
        
        $validater = new Ext_Validate();
        $validater->addValidater(new Add_Setup_Account_Save_Validate_OldPassword($this->_data->oldPassword));
        $validater->addValidater(new Add_Setup_Account_Save_Validate_NewPassword($this->_data->newPassword, $this->_data->confirmNewPassword));
        if(!$validater->isValid()){
            $result['messages'] = $validater->getMessages();
            return new Add_Setup_Password_Save_Result($result['code'], $result['messages']);
        }
        
        $userId = Ext_Auth::getInstance()->getIdentity();
        
        $accountBase = App_Model_DbTable_User_Account_Base::getInstance()->getRowByUserId($userId);
        if(!$accountBase)
        {
            $result['messages'][] = $this->_messager->createMessage(self::IDENTITY_NOT_FOUND);
            return new Add_Setup_Password_Save_Result($result['code'], $result['messages']);
        }
        
        if($accountBase['password'] != $this->_data->oldPassword){
            $result['messages'][] = $this->_messager->createMessage(self::CREDENTIAL_INVALID);
            return new Add_Setup_Password_Save_Result($result['code'], $result['messages']);
        }
        
        $row = array(
            'password' => md5($this->_data->newPassword),
        );
        App_Model_DbTable_User_Account_Base::getInstance()->addOld($row, $userId);
        
        $result['code'] = Add_Setup_Password_Save_Result::SUCCESS;
        return new Add_Setup_Password_Save_Result($result['code'], $result['messages']);
    }
}
